package job.tracker.controller

import job.tracker.controller.UserCommand;
import job.tracker.domain.User;
import grails.validation.ValidationException;

class UserController {

	static allowedMethods = [login: "POST", register: "POST"]

	def index = { render 'hello' }

	def login = { UserCommand cmd ->
		if (!cmd.validate()) {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') {
						fieldErrors = array {
							cmd.errors.fieldErrors.each {
								err(defaultMessage: it.defaultMessage, field: it.field, rejectedValue: it.rejectedValue)
							}
						}
					}
				}
			}
			return
		}

		User foundUser = User.authenticate(cmd.email)

		if (foundUser) {
			session.user = foundUser
			withFormat {
				json {
					render(status: 200, contentType: 'application/json')
				}
			}
		}
		else {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') {  errorMessage = 'Try again!'  }
				}
			}
		}
	}

	def logout = {
		session.user = null
		withFormat {
			json {
				render(status: 200, contentType: 'application/json')
			}
		}
	}

	def register = { UserCommand cmd ->
		if (!cmd.validate()) {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') {
						fieldErrors = array {
							cmd.errors.fieldErrors.each {
								err(defaultMessage: it.defaultMessage, field: it.field, rejectedValue: it.rejectedValue)
							}
						}
					}
				}
			}
			return
		}

		if (User.findByEmail(cmd.email)) {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') {  errorMessage = 'user already registered'  }
				}
			}
			return
		}

		User user = new User(email: cmd.email);

		try {
			user.save()
			withFormat {
				json {
					render(status: 200, contentType: 'application/json') { email = user.email }
				}
			}
		}
		catch (ValidationException e) {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') {
						fieldErrors = array {
							e.errors.fieldErrors.each {
								err(defaultMessage: it.defaultMessage, field: it.field, rejectedValue: it.rejectedValue)
							}
						}
					}
				}
			}
		}
		catch (RuntimeException e) {
			withFormat {
				json {
					render(status: 500, contentType: 'application/json') { errorMessage = e.message }
				}
			}
		}
	}
}

class UserCommand {

	String email

	static constraints = {
		email	(email: true, nullable: false, blank: false)
	}
}
